
/**
 * Content: Synchronized用法-锁定静态代码块、Synchronized-可重入锁
 * --------------------------------------------------
 * Java基础——Synchronized用法: https://juejin.cn/post/6844903705523798029
 */

public class java_1114_synchronized_2 {
    public static void main(String[] args) {
        MyThread mThread1 = new MyThread();
        MyThread mThread2 = new MyThread();

        // 即使是不同实例创建的线程, 也不能同时执行静态代码快
        Thread thread1 = new Thread(mThread1, "XQZ-Thread-OOO");
        Thread thread2 = new Thread(mThread2, "XQZ-Thread-XXX");

        thread1.start();
        thread2.start();
    }
}

class MyThread implements Runnable {
    private static int sign = 0;

    // 修饰静态代码快, 属于类, 不属于某一实例
    public synchronized static void method() {
//    public synchronized void method() {       // 若不加 static, 则该锁属于具体实例
        for (int i = 0; i < 5; i ++) {
            System.out.println(Thread.currentThread().getName() + ":" + (sign++));
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        while (true) {
            method();
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

// Synchronized - 可重入锁 实例
class SynchronizedReentrantDemo {
    private synchronized void setA() throws InterruptedException{
        Thread.sleep(1000);
        System.out.println("进入其他锁!");
        setB();
        System.out.println("重新入锁!");
    }

    private synchronized void setB() throws InterruptedException{
        Thread.sleep(1000);
    }
}